#include <kore/kore.h>
#include <kore/http.h>
#include "head/log.h"
#include "head/index_statis.h"
#include "utils/time_util.h"

int
statis_overview(struct http_request *req)
{
    int line_byte = sizeof(atklog_t);
    FILE *fp = fopen(FILE_PATH, "rb");
    fseek(fp, 0, SEEK_END);
    int file_size = ftell(fp);
    int total = file_size / line_byte;//总条数
    int taday = statis_taday(fp, file_size);
    fclose(fp);

    struct kore_buf	*buf;

    buf = kore_buf_alloc(32);
    kore_buf_appendf(buf, "{");
    kore_buf_appendf(buf, "'total':'%d',", total);
    kore_buf_appendf(buf, "'rule':'%d',", 1);
    kore_buf_appendf(buf, "'taday':'%d',", taday);
    kore_buf_appendf(buf, "'server':'%d'", 1);
    kore_buf_appendf(buf, "}");
    http_response_header(req, "content-type", "text/json");
    http_response(req, 200, buf->data, buf->offset);
    return (KORE_RESULT_OK);
}


int
statis_taday(FILE *fp, int file_size)
{
    time_t t;
    int line_byte = sizeof(atklog_t);
    int	per_page = 10000;
    int taday = 0;
    int current_page = 1;

    t = time(NULL);

    int current_day = get_current_day(time(NULL));

    size_t nread, i;

    int c_page_total_byte, c_page_total_byte_tmp;

    int file_offset, file_offset_tmp;

    atklog_t *buffer;

    while (1){
        c_page_total_byte = line_byte * per_page;
        c_page_total_byte_tmp = c_page_total_byte;

        file_offset = (current_page -1) * c_page_total_byte;
        file_offset_tmp = file_size - file_offset;
        if (file_offset_tmp < c_page_total_byte_tmp) {
            if(file_offset_tmp < 0){
                c_page_total_byte = 32;
            } else {
                c_page_total_byte = file_offset_tmp;
            }
        }

        buffer = malloc(c_page_total_byte);

        fseek(fp, file_offset, SEEK_SET);
        nread = fread(buffer, sizeof(atklog_t), per_page, fp);

        int exist_log = 0;

        for (i = 0; i < nread; i++) {
            atklog_t *s = &buffer[i];
            t = s->time;
            if (t >= current_day) {
                exist_log = 1;
                taday += 1;
            }
        }

        current_page += 1;
        free(buffer);

        if(exist_log == 0){
            break;
        }
    }

    return taday;
}

